import React, { useState, useRef, useCallback } from 'react';
import { Common } from 'UtilsCommon';
import Components from 'Components';
import Base from './base';

const validateImage = (file, pageAxis) => {
    if (!/image/.test(file.type)) { pageAxis.alert("请选择图片"); return; }

    const reg = /\.(jpg|jpeg|png)$/i;
    if (!reg.test(file.name)) { pageAxis.alert("请选择jpg、jpeg、png格式图片"); return; }

    // 大于 10MB
    if (file && file.size > 1024 * 1024 * 10) { pageAxis.alert('请使用小于10MB的图片'); return; }
    return true;
};

const getImage = (file, property) => {
    const { width, height, type, quality, maxWidth, maxHeight, maxSize } = property;

    if (maxSize && file.size < maxSize * 1024) return Promise.resolve(file);

    return Common.compressImage(file, width, height, type || 'image/png', quality || 1, maxWidth, maxHeight).then(res => {
        return Promise.resolve(Common.dataURLtoFile(res, file.name));
    });
};

const uploadImage = (e, pageAxis, property, setValue) => {
    if (e.target.files.length === 0) return;
    const file = e.target.files[0];
    if (!validateImage(file, pageAxis)) return;

    getImage(file, property).then(img => {
        const formData = new FormData();
        formData.append('file', img, img.name);

        const { serviceName, actionName } = property.serviceInterface || {};

        pageAxis.dispatchAction(serviceName, actionName, { formData }).then(res => {
            e.target.value = '';
            if (pageAxis.isSuccessProps(res)) {
                setValue(res.FileUrl);
                if (property.uploadCallback) {
                    const fn = pageAxis.getFunction(property.uploadCallback);
                    fn && fn({ fileUrl: res.FileUrl, property });
                }
            }
            else pageAxis.alert(res.message);
        });
    });
};

const renderButtons = (buttonProperty, removeProperty, property, pageId, value) => {
    if (!removeProperty) return <Components.PropertyItem property={buttonProperty} view={property} pageId={pageId} />;
    return <div style={property.buttonsStyle}>
        <Components.PropertyItem property={buttonProperty} view={property} pageId={pageId} />
        {value && <Components.PropertyItem property={removeProperty} view={property} pageId={pageId} />}
    </div>;
};

export default (props) => {
    const { PropertyItem } = Components;

    const { property, pageAxis, pageId } = Base.getProps(props);
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);
    const [value, setValue] = useState(Base.getInitValue(property));
    const [, setRefreshId] = useState(null);

    const inputFile = useRef(null);

    const onChange = useCallback((e) => {
        uploadImage(e, pageAxis, property, setValue);
    }, [pageAxis, property, setValue]);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setValue = (v) => setValue(v);
    property.getValue = () => value;
    property.refresh = () => setRefreshId(Common.createGuid());

    const uploadImageActionName = 'uploadImageAction_' + property.name;
    pageAxis[uploadImageActionName] = () => inputFile.current.click();

    if (!isVisible || !property.properties || property.properties.length < 2) return null;

    const buttonProperty = property.properties[0];
    const imageProperty = property.properties[1];
    const removeProperty = property.properties.length > 2 ? property.properties[2] : null;

    if (!property.isImgButton) {
        imageProperty.eventActionName = uploadImageActionName;
    }
    imageProperty.value = value;
    buttonProperty.eventActionName = uploadImageActionName;

    return <div style={Base.setStyle(property.style)}>
        {(property.isImgButton || value) && <PropertyItem key={value} property={imageProperty} view={property} pageId={pageId} />}
        {(property.isImgButton || !value) && renderButtons(buttonProperty, removeProperty, property, pageId, value)}
        <input type='file' accept='image/*' onChange={onChange} ref={inputFile} style={{ display: 'none' }} />
    </div>;
};